﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GlobalRadar.UI.NonUI;
using Coding4Fun.Phone.Controls;
using System.Net.NetworkInformation;
using GlobalRadar.Language;

namespace GlobalRadar.UI
{
    public partial class AppGroupManager : PhoneApplicationPage
    {
        ApplicationBarController barControl;

        AppStatusBar myStatus = new AppStatusBar();

        ContextMenu UserGroupMenu = new ContextMenu();
        ContextMenu AllGroupMenu = new ContextMenu();

        public AppGroupManager()
        {
            InitializeComponent();

            InitializeControl();

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show(App.LangVN == true ? ResourceVN.NetworkError : ResourceEn.NetworkError);

                return;
            }
            myStatus.ShowPopup(App.LangVN == true ? ResourceVN.GroupLoading : ResourceEn.GroupLoading);

            if (App.LangVN == true)
            {
                title.Text = ResourceVN.LoginTitle;
                pivotMe.Header = "Nhóm tôi";
                pivotAll.Header="Tất cả";
            }
            else
            {
                title.Text = ResourceEn.LoginTitle;
                pivotMe.Header = "My Group";
                pivotAll.Header="All";
            }
            InitializeMenu();
        }
        private void InitializeMenu()
        {
            MenuItem LeaveGroup = new MenuItem() { Header = App.LangVN == true ? ResourceVN.MenuLeave : ResourceEn.MenuLeave };
            LeaveGroup.Click += ExitGroup_Click;
            UserGroupMenu.Items.Add(LeaveGroup);

            MenuItem JoinGroup = new MenuItem() { Header = App.LangVN == true ? ResourceVN.MenuJoin : ResourceEn.MenuJoin };
            JoinGroup.Click += JoinGroup_Click;
            AllGroupMenu.Items.Add(JoinGroup);
        }
        private void InitializeControl()
        {
            barControl = new ApplicationBarController(this.ApplicationBar);

            if (App.LangVN == true)
            {
                barControl.AddNewButton(ResourceVN.GroupJoin, "/icons/appbar.join.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceVN.GroupDel, "/icons/appbar.delete.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceVN.GroupCreate, "/icons/appbar.add.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceVN.GroupFind, "/icons/appbar.feature.search.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceVN.GroupRefresh, "/icons/appbar.refresh.rest.png", true, ApplicationBarButton_Click);
            }
            else
            {
                barControl.AddNewButton(ResourceEn.GroupDel, "/icons/appbar.delete.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceEn.GroupCreate, "/icons/appbar.add.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceEn.GroupFind, "/icons/appbar.feature.search.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceEn.GroupRefresh, "/icons/appbar.refresh.rest.png", true, ApplicationBarButton_Click);
            }

            LoadListGroup();

            LoadAllGroup();
        }
        private void LoadListGroup()
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetListGroupAsync(Global.UserInfo.Username);

            client.GetListGroupCompleted += (s, args) =>
            {
                if (args.Result == null) return;

                List<List<object>> result = Json.ParseTable(args.Result);

                myGroup.Items.Clear();

                foreach (List<object> ls in result)
                {
                    if (ls.Count >= 2)
                    {
                        GroupItemData item = new GroupItemData();
                        item.Id = int.Parse(ls[0].ToString());
                        item.TextTitle = ls[1].ToString();
                        item.UserOwner = ls[2].ToString();
                        item.MyOwner = int.Parse(ls[3].ToString());
                        item.Status = int.Parse(ls[4].ToString());
                        if (item.Status == 1)
                            myGroup.Items.Add(item);
                    }
                }
            };
        }
        private void LoadAllGroup()
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetAllGroupAsync(0,30);

            client.GetAllGroupCompleted += (s, args) =>
            {
                List<List<object>> result = Json.ParseTable(args.Result);
                allGroup.Items.Clear();
                foreach (List<object> ls in result)
                {
                    if (ls.Count >= 2)
                    {
                        GroupItemData item = new GroupItemData();

                        item.Id = int.Parse(ls[0].ToString());
                        item.TextTitle = ls[1].ToString();
                        item.UserOwner = ls[2].ToString();
                        item.MyOwner = int.Parse(ls[3].ToString());
                        item.Status = int.Parse(ls[4].ToString());
                        allGroup.Items.Add(item);
                    }
                }
                myStatus.Abort();    
            };
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = MainPriviot.SelectedIndex;
            switch (i)
            {
                case 0:
                    if (App.LangVN == true)
                    {
                        barControl.ShowButtons(ResourceVN.GroupCreate, ResourceVN.GroupRefresh);
                    }
                    else
                        barControl.ShowButtons(ResourceEn.GroupCreate, ResourceEn.GroupRefresh);
                    break;
                case 1:
                    if (App.LangVN == true)
                    {
                        barControl.ShowButtons(ResourceVN.GroupCreate, ResourceVN.GroupFind, ResourceVN.GroupRefresh);
                    }
                    else
                        barControl.ShowButtons(ResourceEn.GroupCreate, ResourceEn.GroupFind, ResourceEn.GroupRefresh);
                    break;
            }
        }

        private void JoinGroup_Click(object sender, RoutedEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show(App.LangVN == true ? ResourceVN.NetworkError : ResourceEn.NetworkError);

                return;
            }

            string header = (sender as MenuItem).Header.ToString();

            ListBoxItem listItem = this.allGroup.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            if (listItem != null)
            {
                mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                GroupItemData item = listItem.Content as GroupItemData;

                client.CreateLinkerAsync(item.Id, Global.UserInfo.UserID, 0, 2);

                client.CreateLinkerCompleted += (s, args) =>
                {
                    LoadListGroup();
                };
            }
        }

        private void allGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(allGroup.SelectedItem!=null)
            {
                if (App.LangVN == true)
                {
                    barControl.ShowButtons(ResourceVN.GroupCreate, ResourceVN.GroupFind, ResourceVN.GroupRefresh);
                }
                else
                    barControl.ShowButtons(ResourceEn.GroupCreate, ResourceEn.GroupFind, ResourceEn.GroupRefresh);

                //barControl.ShowButtons("Xin vào", "Tạo nhóm", "Tìm kiếm","làm tươi");
            }
            else
                 if (App.LangVN == true)
                {
                    barControl.ShowButtons(ResourceVN.GroupCreate, ResourceVN.GroupFind);
                }
                else

                    barControl.ShowButtons(ResourceEn.GroupCreate, ResourceEn.GroupFind);
        }

        private void ExitGroup_Click(object sender, RoutedEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show(App.LangVN == true ? ResourceVN.NetworkError : ResourceEn.NetworkError);

                return;
            }
            string header = (sender as MenuItem).Header.ToString();

            ListBoxItem listItem = this.myGroup.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            if (listItem != null)
            {
                mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                GroupItemData item = listItem.Content as GroupItemData;
                if (item.MyOwner == 1)
                {
                    MessageBoxResult result = MessageBox.Show(App.LangVN == true ? ResourceVN.GroupLeaderLeave : ResourceEn.GroupLeaderLeave, App.LangVN == true ? ResourceVN.LeaveGroupTitle : ResourceEn.LeaveGroupTitle, MessageBoxButton.OKCancel);

                    if (result == MessageBoxResult.OK)
                    {
                        client.RemoveGroupAsync(item.Id);

                        client.RemoveGroupCompleted += (s, args) =>
                        {
                            if (args.Result == true)
                            {
                                if (App.LangVN == true)

                                    MessageBox.Show("Nhóm:" + item.TextTitle +" đã bị giải tán");
                                else
                                    MessageBox.Show("Group:" + item.TextTitle + " is disbanded");

                                LoadListGroup();

                                LoadAllGroup();
                            }
                        };
                    }
                }
                else
                {
                    MessageBoxResult result = MessageBox.Show(App.LangVN == true ? ResourceVN.LeaveGroupContent : ResourceEn.LeaveGroupContent, App.LangVN == true ? ResourceVN.LeaveGroupTitle : ResourceEn.LeaveGroupTitle, MessageBoxButton.OKCancel);

                    if (result == MessageBoxResult.OK)
                    {
                        client.RemoveLinkerAsync(item.Id, Global.UserInfo.UserID);

                        client.RemoveLinkerCompleted += (s, args) =>
                        {
                            if (args.Result == true)
                            {
                                MessageBox.Show((App.LangVN == true ? ResourceVN.LeaveGroupSucess : ResourceEn.LeaveGroupSucess) + item.TextTitle);

                                LoadListGroup();
                            }
                        };
                    }
                }
            }
        }

        private void ApplicationBarButton_Click(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show(App.LangVN == true ? ResourceVN.NetworkError : ResourceEn.NetworkError);

                return;
            }

            ApplicationBarIconButton btn = (ApplicationBarIconButton)sender;

            string text = btn.Text.ToLower();

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (text == (App.LangVN == true ? ResourceVN.GroupJoin.ToLower() : ResourceEn.GroupJoin.ToLower()))
            {
                ListBoxItem listItem = this.allGroup.SelectedItem as ListBoxItem;

                if (listItem != null)
                {
                    GroupItemData item = listItem.Content as GroupItemData;

                    MessageBox.Show(item.TextTitle);

                    client.CreateLinkerAsync(item.Id, Global.UserInfo.UserID, 0, 2);

                    client.CreateLinkerCompleted += (s, args) =>
                    {
                        LoadListGroup();
                    };
                }
            }

            if (text == (App.LangVN == true ? ResourceVN.GroupRefresh.ToLower() : ResourceEn.GroupRefresh.ToLower()))
            {
                myStatus.ShowPopup(App.LangVN == true ? ResourceVN.RefeshContent : ResourceEn.RefeshContent);  
                LoadAllGroup();
                LoadListGroup();
            }

            if (text == (App.LangVN == true ? ResourceVN.GroupFind.ToLower() : ResourceEn.GroupFind.ToLower()))
            {
                InputPrompt input = new InputPrompt();
                input.Completed += (s, args) =>
                {
                    client.SearchGroupCompleted += (send, recive) =>
                    {
                        List<List<object>> result = Json.ParseTable(recive.Result);

                        if (result == null)
                        {
                            MessageBox.Show((App.LangVN == true ? ResourceVN.ArletResultFound : ResourceEn.ArletResultFound));
                            return;
                        }
                        allGroup.Items.Clear();

                        foreach (List<object> ls in result)
                        {
                            if (ls.Count >= 2)
                            {
                                GroupItemData item = new GroupItemData();

                                item.Id = int.Parse(ls[0].ToString());
                                item.TextTitle = ls[1].ToString();
                                item.UserOwner = ls[2].ToString();
                                item.MyOwner = int.Parse(ls[3].ToString());
                                item.Status = int.Parse(ls[4].ToString());
                                allGroup.Items.Add(item);
                            }
                        }
                    };
                    client.SearchGroupAsync(args.Result);
                };
                input.Title = App.LangVN == true ? ResourceVN.GroupFindTitle : ResourceEn.GroupFindTitle;
                input.Message = App.LangVN == true ? ResourceVN.GroupFindContent : ResourceEn.GroupFindContent;
                input.Show();
            }

            if (text == (App.LangVN == true ? ResourceVN.GroupCreate.ToLower() : ResourceEn.GroupCreate.ToLower()))
            {
                InputPrompt input = new InputPrompt();
                input.Completed += (s, args) =>
                {
                    if (args.Result != "")
                    {
                        client.CreateGroupCompleted += (send, recive) =>
                        {
                            LoadAllGroup();
                            LoadListGroup();
                        };
                        client.CreateGroupAsync(Global.UserInfo.UserID, args.Result, 1, 1);
                    }
                };
                input.Title = App.LangVN == true ? ResourceVN.GroupCreateTitle : ResourceEn.GroupCreateTitle;
                input.Message = App.LangVN == true ? ResourceVN.GroupCreateContent : ResourceEn.GroupCreateContent;
                input.Show();
            }
        }

        private void myGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
          //  
        }

        private void myGroup_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (FrameworkElement)e.OriginalSource;

            if (item != null)
            {
                GroupItemData data = item.DataContext as GroupItemData;
                
                NavigationService.Navigate(new Uri("/UI/AppGroupUser.xaml?groupid="+data.Id+"&owner="+data.MyOwner, UriKind.RelativeOrAbsolute));
            }
        }


        private void myGroup_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var item = (FrameworkElement)e.OriginalSource;
            if (item != null)
                ContextMenuService.SetContextMenu(item, UserGroupMenu);
        }

        private void allGroup_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var item = (FrameworkElement)e.OriginalSource;
            if (item != null)
                ContextMenuService.SetContextMenu(item, AllGroupMenu);
        }
    }
}